/******************************************************************
 *
 *    Java Lib For JavaWeb, Powered By Shenzhen WEI YI KE JI .
 *
 *    Copyright (c) 2017-2027 Digital Telemedia Co.,Ltd
 *    http://www.d-telemedia.com/
 *
 *    Package:     com.theyeasy.dvmini.util
 *
 *    Filename:    ImageUtil.java
 *
 *    Description: TODO(用一句话描述该文件做什么)
 *
 *    Copyright:   Copyright (c) 2017-2027
 *
 *    Company:     Theyeasy Telemedia Co.,Ltd
 *
 *    @author:     hm
 *
 *    @version:    1.0.0
 *
 *    Create at:   2017年10月24日 下午3:12:50
 *
 *    Revision:
 *
 *    2017年10月24日 下午3:12:50
 *        - first revision
 *
 *****************************************************************/
package com.theyeasy.dvmini.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.swing.ImageIcon;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.common.base.Strings;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import sun.awt.image.ImageFormatException;

/**
 * @ClassName ImageUtil
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author hm
 * @Date 2017年10月24日 下午3:12:50
 * @version 1.0.0
 */
public class ImageUtil {

    /*
     * 生成海报图片
     */
    public final static String GenerateJPGImg(String imageurl, String qrCode, int qrX, int qrY, int qrW)
            throws ImageFormatException, IOException {
        String timeMillis = "";
        InputStream is = null;
        OutputStream os = null;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getRequest();
            String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/res/upload/miniposter");
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String newrealPath = request.getSession().getServletContext().getRealPath("/WEB-INF/");
            String sourceImg = imageurl = newrealPath + imageurl.replace("/dvmini", "");
            System.out.println("sourceimg:" + sourceImg);
            is = new FileInputStream(sourceImg);

            // 通过JPEG图象流创建JPEG数据流解码器
            JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is);
            // 解码当前JPEG数据流，返回BufferedImage对象
            BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
            // 得到画笔对象
            Graphics g = buffImg.getGraphics();
            // 附加的二维码
            if (!Strings.isNullOrEmpty(qrCode)) {// 判断二维码不为空
                ImageIcon imgIcon = new ImageIcon(qrCode);
                // 得到Image对象。
                Image img = imgIcon.getImage();
                g.drawImage(img, qrX, qrY, qrW, qrW, null);
            }

            // 设置颜色。
            g.setColor(Color.white);
            // 最后一个参数用来设置字体的大小
            Font f = new Font("宋体", Font.BOLD, 44);
            g.setFont(f);
            g.dispose();

            timeMillis = System.currentTimeMillis() + "";
            os = new FileOutputStream(realPath + "/" + timeMillis + ".jpg");
            // 创键编码器，用于编码内存中的图象数据。
            JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
            en.encode(buffImg);

        } catch (com.sun.image.codec.jpeg.ImageFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("海报生成失败：" + e.getMessage());
        } catch (Exception ee) {
            System.out.println("海报生成失败：" + ee.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            is = null;
            os = null;
        }
        return "/dvmini/res/upload/miniposter/" + timeMillis + ".jpg";
    }

    /**
     * 缩放图像（按高度和宽度缩放）
     * 
     * @param srcImageFile
     *            源图像文件地址
     * @param result
     *            缩放后的图像地址
     * @param height
     *            缩放后的高度
     * @param width
     *            缩放后的宽度
     * @param bb
     *            比例不对时是否需要补白：true为补白; false为不补白;
     */
    public final static void scale2(String srcImageFile, String result, int height, int width, boolean bb) {
        try {
            double ratio = 0.0; // 缩放比例
            File f = new File(srcImageFile);
            BufferedImage bi = ImageIO.read(f);
            @SuppressWarnings("static-access")
            Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
            // 计算比例
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                if (bi.getHeight() > bi.getWidth()) {
                    ratio = (new Integer(height)).doubleValue() / bi.getHeight();
                } else {
                    ratio = (new Integer(width)).doubleValue() / bi.getWidth();
                }

                AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            if (bb) {// 补白
                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == itemp.getWidth(null))
                    g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null),
                            itemp.getHeight(null), Color.white, null);
                else
                    g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null),
                            itemp.getHeight(null), Color.white, null);
                g.dispose();
                itemp = image;
            }
            BufferedImage bufImg = new BufferedImage(itemp.getWidth(null), itemp.getHeight(null),
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = bufImg.createGraphics();
            g.drawImage(itemp, 0, 0, null);
            g.dispose();
            ImageIO.write((BufferedImage) bufImg, "JPEG", new File(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
